package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.UserRoles;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.EnterpriseVo;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.antdesignbackend.backend.service.UserRolesService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/harmlessenterprise")
public class HarmlessEnterpriseController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @Autowired
    EnterpriseService enterpriseService;

    @Autowired
    UserService userService;

    @Autowired
    UserRolesService userRolesService;

    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "harmlessenterprise/index";
    }
    @GetMapping("/details")
    @AuthToken
    public String Details(@RequestParam(value = "eid",required = false) Integer eid, Model model) {
        model.addAttribute("eid",eid);
        return "details/index3";
    }

    @GetMapping("/personal")
    @AuthToken
    public String bdetails(@RequestParam(value = "eid",required = false) Integer eid, Model model) {
        //根据当前企业的信息
        Enterprise enterprise = enterpriseService.getById(getLoginEnterpriseId());
        model.addAttribute("enterprise",enterprise);
        return "slaughter/personal";
    }
    /**
     * 分页查询
     * @param enterpriseVo
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody EnterpriseVo enterpriseVo, HttpServletRequest request) {
        ReturnVO result = new ReturnVO();
        List<EnterpriseVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<EnterpriseVo> queryWrapper = new QueryWrapper<>();
            //判断用户权限
            Users users = userService.getById(getLoginUserId());
            if (users.getAuthType() == 1){ //地市权限
                queryWrapper.eq("cityCode",users.getAuthCity());
            }else if (users.getAuthType() == 2){ //区县权限
                queryWrapper.eq("districtCode",users.getAuthDistrict());
            }else if (users.getAuthType() == 3){
                queryWrapper.eq("townCode",users.getAuthTown());
            }else {
                return result;
            }
            queryWrapper.eq("types",2); //无害化
            //根据地市查询
            if(enterpriseVo.getCityCode() != null && !enterpriseVo.getCityCode().equals("-1")){
                queryWrapper.eq("cityCode",enterpriseVo.getCityCode()); //养殖企业
            }
            if(enterpriseVo.getDistrictCode() != null && !enterpriseVo.getDistrictCode().equals("-1")){
                queryWrapper.eq("districtCode",enterpriseVo.getDistrictCode()); //养殖企业
            }
            if(enterpriseVo.getTownCode() != null && !enterpriseVo.getTownCode().equals("-1")){
                queryWrapper.eq("townCode",enterpriseVo.getTownCode()); //养殖企业
            }
            if (enterpriseVo.getEnterpriseName() != null && !enterpriseVo.getEnterpriseName().equals("")){
                queryWrapper.like("enterpriseName",enterpriseVo.getEnterpriseName());
            }
            if (enterpriseVo.getUserName() != null && !enterpriseVo.getUserName().equals("")){
                queryWrapper.like("userName",enterpriseVo.getUserName());
            }
            if (enterpriseVo.getExamine() != null){
                if (enterpriseVo.getExamine() == 3){ //查询已审核的企业，包括通过和未通过的
                    queryWrapper.eq("examine",1).or().eq("examine",2);
                }else {
                    queryWrapper.eq("examine",enterpriseVo.getExamine());
                }
            }
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=enterpriseService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= enterpriseService.search(queryWrapper,new Page<EnterpriseVo>(enterpriseVo.pageIndex,enterpriseVo.pageSize));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    @PostMapping("/tableSearchMe/{eid}")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearchMe(@PathVariable("eid") Integer eid) {
        ReturnVO result = new ReturnVO();
        List<EnterpriseVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<EnterpriseVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("types",2); //无害化
            queryWrapper.eq("enterpriseId",eid); //无害化企业
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=enterpriseService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= enterpriseService.search(queryWrapper,new Page<EnterpriseVo>(1,2));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 修改
     * @param enterprise
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    @AuthToken
    public ReturnVO edit(@RequestBody Enterprise enterprise) {
        try {
            enterpriseService.updateById(enterprise);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 重置密码
     * @param enterprise
     * @return
     */
    @PostMapping("/resetPassword")
    @ResponseBody
    @AuthToken
    public ReturnVO resetPassword(@RequestBody Enterprise enterprise) {
        try {
            UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("Eid",enterprise.getEnterpriseId());
            updateWrapper.eq("Grade",1);
            updateWrapper.set("Password", DigestUtils.md5DigestAsHex(WebConfig.password.getBytes()));
            userService.update(updateWrapper);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 审核
     * @param enterprise
     * @return
     */
    @PostMapping("/toExamine")
    @ResponseBody
    @AuthToken
    public ReturnVO toExamine(@RequestBody Enterprise enterprise) {
        //设置审核人员
        enterprise.setExamineUid(getLoginUserId());
        //审核时间
        enterprise.setExamineTime(new Date());
        try {
            if (enterpriseService.updateById(enterprise)){ //创建users
                //根据eid查询到对应的企业
                Enterprise enterprise1 = enterpriseService.getById(enterprise.getEnterpriseId());
                if (enterprise1 != null){
                    if (enterprise1.getExamine() == 1){ //审核通过
                        Users users = new Users();
                        users.setUserName(enterprise1.getLoginID()); //登录名
                        users.setPassword(enterprise1.getPassword()); //密码
                        users.setEid(enterprise1.getEnterpriseId()); //企业id
                        users.setGrade(1);  //一级账号
                        users.setActivity(1); //激活
                        users.setUserType(5); //无害化处理企业
                        users.setRealName(enterprise1.getUserName());
                        users.setCreateName(getLoginUserName());
                        Date date = new Date();
                        String currentDateTime = CalendarDate.dateToStr(date,"yyyy-MM-dd HH:mm:ss");
                        users.setCreateDateTime(currentDateTime);
                        users.setPhone(enterprise1.getPhone());
                        users.setAuthCity(enterprise1.getCityCode() != null ? Integer.parseInt(enterprise1.getCityCode()) : 0);
                        users.setAuthDistrict(enterprise1.getDistrictCode() != null ? Integer.parseInt(enterprise1.getDistrictCode()) : 0);
                        users.setAuthTown(enterprise1.getTownCode() != null ? Integer.parseInt(enterprise1.getTownCode()) : 0);
                        if (userService.save(users)){
                            //设置用户角色信息
                            UserRoles userRoles = new UserRoles();
                            userRoles.setUserID(users.getUserID());
                            userRoles.setRoleID(5); //屠宰企业
                            userRolesService.save(userRoles);
                            return new ReturnVO();
                        }else {
                            return new ReturnVO(ReturnCode.FAIL);
                        }
                    }
                }
            }
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 获得所有审核通过并且启用的无害化处理企业
     * @return
     */
    @GetMapping("/getHarmlessId")
    @ResponseBody
    @AuthToken
    public  List<Enterprise> getHarmlessId1() {
        List<Enterprise> list = new ArrayList<>();
        try {
            QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("types",2); //无害化企业企业
            queryWrapper.eq("examine",1);
            queryWrapper.eq("activity",1);
            list=enterpriseService.list(queryWrapper);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return list;
    }
}
